package link.jfire.jnet.client;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class ResponseFuture implements Future<Object>
{
    protected volatile Object    result = null;
    protected Lock               lock;
    protected Condition          hasResponse;
    protected volatile Throwable e;
                                 
    public ResponseFuture(Lock lock, Condition hasResponse)
    {
        this.lock = lock;
        this.hasResponse = hasResponse;
    }
    
    @Override
    public boolean cancel(boolean mayInterruptIfRunning)
    {
        return false;
    }
    
    @Override
    public boolean isCancelled()
    {
        return false;
    }
    
    @Override
    public boolean isDone()
    {
        return result != null;
    }
    
    @Override
    public Object get() throws InterruptedException, ExecutionException
    {
        lock.lock();
        try
        {
            while (result == null)
            {
                hasResponse.await();
            }
            if (e != null)
            {
                throw new ExecutionException(e);
            }
            return result;
        }
        
        finally
        {
            lock.unlock();
        }
        
    }
    
    @Override
    public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
    {
        lock.lock();
        try
        {
            while (result == null)
            {
                hasResponse.await(timeout, unit);
            }
            return result;
        }
        finally
        {
            lock.unlock();
        }
    }
    
}
